import 'dart:async';

import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter/material.dart';
import 'package:smartloan_mdc/extension/extension.dart';

import '../../res/theme.dart';

class SmsCode extends StatefulWidget {
  const SmsCode({
    Key? key,
    required this.controller,
    this.completeText
  }) : super(key: key);

  final SmsController controller;
  final String? completeText;

  @override
  State<SmsCode> createState() => _SmsCodeState();
}

class _SmsCodeState extends State<SmsCode> {

  bool isCounting = false;

  @override
  void initState() {
    SmsCodeListener listener = SmsCodeListener(
        onCount: (value) {
          if (mounted) {
            setState(() {
              isCounting = true;
            });
          }
        },
        onComplete: () {
          if (mounted) {
            setState(() {
              isCounting = false;
            });
          }
        }
    );
    widget.controller.addListener(listener);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      // decoration: BoxDecoration(
      //   border: Border.all(color: AppTheme.button),
      //   borderRadius: const BorderRadius.all(Radius.circular(90))
      // ),
      padding: EdgeInsets.symmetric(vertical: 2.h, horizontal: 5.w),
      child: isCounting
          ? '${widget.controller.count}s'.sText(color: Colors.white)
          : (widget.completeText ?? 'Get again').sText(color: Colors.white),
    );
  }
}

class SmsController {

  int _count = 60;
  bool _counting = false;
  Timer? _timer;

  int get count => _count;
  bool get isCounting => _counting;
  List<SmsCodeListener> subscribe = [];

  void addListener(SmsCodeListener listener) {
    subscribe.add(listener);
  }

  void start({int initCount = 60}) {
    if (_counting) {
      // debugPrint('正在计数,返回');
      return;
    }
    _counting = true;
    // doCount(_count);
    // _count = initCount - 1;
    _count = initCount;
    doCount(_count);

    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_count > 1) {
        _count -= 1;
        doCount(_count);
      } else {
        _counting = false;
        doComplete();
        _timer?.cancel();
        _timer = null;
      }
    });
  }

  void interrupt() {
    _count = 60;
    _counting = false;
    _timer?.cancel();
    _timer = null;
  }

  void dispose() {
    _timer?.cancel();
  }

  void doCount(value) {
    for (var element in subscribe) {
      element.onCount?.call(value);
    }
  }

  void doComplete() {
    for (var element in subscribe) {
      element.onComplete?.call();
    }
  }

}

class SmsCodeListener {

  SmsCodeListener({
    this.onCount,
    this.onComplete
  });

  Function? onCount;
  Function? onComplete;
}